using System;
using System.Collections.Generic;
using System.Timers;
using Android.OS;
using Android.Views;
using Android.Widget;

using JmShared;
using Fragment = Android.Support.V4.App.Fragment;

namespace jivemessenger
{
    public class ChatControl : Fragment
    {
        private ListView _listview;
        private ConversationArrayAdapter _adapter;
        //public TextView ConversationTextView;
        private EditText InputText;
        public bool IsPm;
        public UserInfo PmTarget;
        public int MessageID;
        private View _rootView;
        public event EventHandler<NewChatMessageEventArgs> SendMessageEvent;
        private bool IsKeyboardOpen { get; set; }

        public override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            //  AddItems();
        }

        public void AddChatBubbles(IEnumerable<ChatBubble> items)
        {
            foreach (ChatBubble bubble in items)
                _adapter.AddChatBubble(bubble);
        }

        public List<ChatBubble> GetChatBubbles()
        {
            return _adapter.GetChatBubbleList();
        }

        public void DisplayChatBubble(UserInfo user, string text, DateTime timestamp)
        {
            //bool bubbleLeft = user == null || user.UserName != Client.CurrentUserInfo.UserName;
            StaticSettings.GlobalContext.RunOnUiThread(() =>
                {
                    this._adapter.AddChatBubble(new ChatBubble(text, user, timestamp));
                    this._listview.SetSelection(this._adapter.GetChatBubbleCount() - 1);
                });
        }
        public override void OnViewCreated(View view, Bundle savedInstanceState)
        {
            // Create your fragment here
            this._listview = (ListView)view.FindViewById<ListView>(Resource.Id.listMessages);
            this._adapter = new ConversationArrayAdapter(view.Context, Resource.Layout.ChatBubbleListItem);
            this._listview.Adapter = this._adapter;

            InputText = (EditText)view.FindViewById(Resource.Id.chatET);
            InputText.KeyPress += (s, e) =>
            {
                if (e.Event.KeyCode == Keycode.Enter && e.Event.Action == KeyEventActions.Down)
                {

                    SendMessage(s, e);
                }
            };
            Button sendButton = (Button)view.FindViewById(Resource.Id.sendBtn);
            sendButton.Click += (s, e) => this.SendMessage(s, null);

            GlobalLayoutListener gll = new GlobalLayoutListener(
            delegate
            {

                Android.Graphics.Rect r = new Android.Graphics.Rect();
                _rootView.GetWindowVisibleDisplayFrame(r);

                int heightDiff = _rootView.RootView.Height - (r.Bottom - r.Top);
                if (heightDiff > 100 && !IsKeyboardOpen)
                {
                    _listview.SetSelection(_adapter.GetChatBubbleCount() - 1);
                    IsKeyboardOpen = true;
                }
                else
                    IsKeyboardOpen = false;
            });

            _rootView = view;// Activity.FindViewById<View>(Resource.Id.GroupchatBaseLayout);
            _rootView.ViewTreeObserver.AddOnGlobalLayoutListener(gll);
        }



        void SendMessage(object sender, View.KeyEventArgs e)
        {
            if (!Client.IsLoggedIn)
            {
                MessageBox.Show("Not logged in");
                return;
            }
            if (SendMessageEvent != null)
            {
                ChatMessage msg = new ChatMessage()
                    {
                        Message = InputText.Text,
                        MessageType = IsPm ? MessageType.PM : MessageType.Message,
                        Sender = Client.CurrentUserInfo,
                        UserInfo = PmTarget != null ? new UserInfo[1] { PmTarget } : null,
                        MessageID = MessageID++
                    };
                SendMessageEvent(this, new NewChatMessageEventArgs(msg));

                this.DisplayChatBubble(Client.CurrentUserInfo, InputText.Text, DateTime.Now);
                InputText.Text = "";
            }
            else
                this.DisplayChatBubble(Client.CurrentUserInfo, "Not connected", DateTime.Now);
        }

        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            var v = inflater.Inflate(Resource.Layout.ChatControl, container, false);
            return v;
        }

        class GlobalLayoutListener : Java.Lang.Object, ViewTreeObserver.IOnGlobalLayoutListener
        {
            Action on_global_layout;
            public GlobalLayoutListener(Action onGlobalLayout)
            {
                on_global_layout = onGlobalLayout;
            }

            public void OnGlobalLayout()
            {
                on_global_layout();
            }
        }

    }
}